package com.firstclass.exception.handler;


import com.firstclass.exception.BadRequestException;
import com.firstclass.utils.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 统一异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     *
     * @param ex   异常类
     * @return     返回值
     */
    @ExceptionHandler(value = BadRequestException.class)
    public String badRequestHandler(BadRequestException ex) {
        return buildResponseEntity(ApiError.error(ex.getStatus(), ex.getMessage()));
    }

    /**
     * 处理所有未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public String handleException(Throwable e) {
        return buildResponseEntity(ApiError.error(e.getMessage()));
    }

    /**
     * 统一返回
     *
     * @param apiError
     * @return
     */
    private String buildResponseEntity(ApiError apiError) {
        return R.error(apiError.getStatus(), apiError.getMsg());
    }
}
